package com.captain.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * 文件上传工具
 */
public class FileUpload {
    private static String VIRTUAL_PATH="/avatar/";
    private static String REAL_PATH="D:\\JAVAEE\\upload\\avatar\\";

    public static String saveAvatar(MultipartFile multipartFile){
        //获取头像的后缀名
        String originalName=multipartFile.getOriginalFilename();
        String ext=originalName.substring(originalName.indexOf('.')+1).toLowerCase();
        //创建新名字
        String filename= UuidUtil.getUUID()+"."+ext;
        //创建文件
        File file=new File(REAL_PATH+filename);
        //判断文件不存在就创建
        if (!file.exists()&&!file.mkdir()) return null;
        try{
            multipartFile.transferTo(file);
            return VIRTUAL_PATH+filename;
        }catch (Exception e){
            return null;
        }
    }
}
